package com.htgd.gardenexpo.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.htgd.gardenexpo.dao.*;
import com.htgd.gardenexpo.dto.BindingBraceletDTO;
import com.htgd.gardenexpo.dto.CompetitionDTO;
import com.htgd.gardenexpo.dto.GeConUserCompeteDTO;
import com.htgd.gardenexpo.dto.PostSportsDataDTO;
import com.htgd.gardenexpo.entity.*;
import com.htgd.gardenexpo.page.CompeteQuery;
import com.htgd.gardenexpo.page.CompeteUserQuery;
import com.htgd.gardenexpo.service.DeviceService;
import com.htgd.gardenexpo.service.GeConUserCompeteService;
import com.htgd.gardenexpo.service.WxUserStepService;
import com.htgd.gardenexpo.utils.HttpRequest;
import com.htgd.gardenexpo.utils.TokenUtil;
import com.htgd.gardenexpo.vo.*;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.DatatypeConverter;
import java.math.BigDecimal;
import java.security.AlgorithmParameters;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.IntStream;

/**
 * @author: 王秀田
 * @date: 2024/11/29 13:19
 * @description: TODO
 */
@Service
public class GeConUserCompeteServiceImpl extends ServiceImpl<GeConUserCompeteMapper, GeConUserCompete> implements GeConUserCompeteService {

    @Autowired
    private GeConUserCompeteMapper geConUserCompeteMapper;

    @Value("${device.binding_url}")
    private String bindingUrl;

    @Value("${device.item_ids}")
    private String itemIds;

    @Value("${device.tenant_id}")
    private String tenantId;

    @Value("${device.device_type}")
    private String deviceType;

    @Value("${device.race_up_url}")
    private String raceUpUrl;

    @Value("${device.bracelet_url}")
    private String braceletUrl;

    @Autowired
    private GeMyAddressDao geMyAddressDao;

    @Autowired
    private GeConCompetitionSportsMapper geConCompetitionSportsMapper;

    @Autowired
    private GeConLeisureSportsMapper geConLeisureSportsMapper;

    @Autowired
    private WxUserStepMapper wxUserStepMapper;

    @Autowired
    private GeConFreeSportsMapper geConFreeSportsMapper;

    @Autowired
    private WxUserDao wxUserDao;

    @Autowired
    private DeviceService deviceService;



    @Override
    public PageInfo<HashMap> pageList(CompeteQuery competeQuery) {
        PageHelper.startPage(competeQuery.getPageNum(), competeQuery.getPageSize());
        List<HashMap> list = new ArrayList<>();
        if(Objects.equals(competeQuery.getSportsType(),"1")){
            list = geConUserCompeteMapper.queryList(competeQuery);
        }
        if(Objects.equals(competeQuery.getSportsType(),"2")){
            list = geConUserCompeteMapper.pageList(competeQuery);
        }
        return new PageInfo<>(list);
    }


    @Override
    public PageInfo<GeConUserCompeteVO> listNew(CompeteUserQuery competeUserQuery) {
        PageHelper.startPage(competeUserQuery.getPageNum(), competeUserQuery.getPageSize());
        List<GeConUserCompeteVO> list = geConUserCompeteMapper.listNew(competeUserQuery);
        return new PageInfo<>(list);
    }



    @Transactional
    @Override
    public synchronized CommonResult add(GeConUserCompeteDTO geConUserCompete, HttpServletRequest request) {
        JSONObject body = new JSONObject();

        // 获取当前时间
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime now = LocalDateTime.now();
        //获取openID
        String accessToken = request.getHeader("Access_token");
        String openId = TokenUtil.getUsernameFromToken(accessToken);
        //检查是否已经报名
        GeConUserCompete geConUserCompete2 = geConUserCompeteMapper.selectOne(
            new LambdaQueryWrapper<GeConUserCompete>().eq(GeConUserCompete::getOpenId,openId)
             .eq(GeConUserCompete::getSportsType,geConUserCompete.getSportsType())
            .eq(GeConUserCompete::getMotionId,geConUserCompete.getMotionId())
            .eq(GeConUserCompete::getStatus,"1"));
        if(Objects.nonNull(geConUserCompete2)){
            return CommonResult.error("您已报名，不可重复报名");
        }
        //赛事
        if(Objects.equals(geConUserCompete.getSportsType(),"1")){
            GeConCompetitionSports geConCompetitionSports = geConCompetitionSportsMapper.selectById(geConUserCompete.getMotionId());
            if (!now.isAfter(geConCompetitionSports.getStartDate()) || !now.isBefore(geConCompetitionSports.getEndDate())) {
                return CommonResult.error("当前时间不在报名时间范围内");
            }
            body.put("name",geConCompetitionSports.getName());
            body.put("route",geConCompetitionSports.getRouteId());
            body.put("startTime",geConCompetitionSports.getStartTime().format(formatter));
            body.put("endTime",geConCompetitionSports.getEndTime().format(formatter));

        }
        if(Objects.equals(geConUserCompete.getSportsType(),"2")){
            GeConLeisureSports geConLeisureSports = geConLeisureSportsMapper.selectById(geConUserCompete.getMotionId());
            if (!now.isAfter(geConLeisureSports.getStartDate()) || !now.isBefore(geConLeisureSports.getEndDate())) {
                return CommonResult.error("当前时间不在报名时间范围内");
            }
            body.put("name",geConLeisureSports.getName());
            body.put("fallowType",Long.valueOf(geConLeisureSports.getRule()));
            body.put("startTime",geConLeisureSports.getStartTime().format(formatter));
            body.put("endTime",geConLeisureSports.getEndTime().format(formatter));
        }

        //向甲板推送数据
        body.put("raceId",Long.valueOf(geConUserCompete.getMotionId()));
        body.put("itemId",itemIds);
        body.put("raceType",Long.valueOf(geConUserCompete.getSportsType()));
        body.put("userId",Long.valueOf(geConUserCompete.getUserId()));

        Map<String, Object> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Tenant-Id", tenantId);
        try {
            headers.put("Authorization", "Bearer " + deviceService.deviceLogin());
            String result = HttpRequest.sendHttpPostRequest(bindingUrl, null, headers,body.toString());
            if (result != null && result != "") {
                JSONObject jsonObject = (JSONObject) JSONObject.parse(result);
                Boolean ok = (Boolean) jsonObject.get("ok");
                Integer code = (Integer) jsonObject.get("code");
                if (!ok && code != 0) {
                    System.out.println("报名信息推送失败:{}"+result);
                    return CommonResult.error("报名信息推送失败");
                }
            }else {
                return CommonResult.error("报名信息推送失败");
            }
        }catch (Exception e){
            return CommonResult.error("向第三方查询用户注册信息异常");
        }
        //插入数据
        GeConUserCompete geConUserCompete1 = new GeConUserCompete();
        BeanUtils.copyProperties(geConUserCompete,geConUserCompete1);
        geConUserCompete1.setOpenId(openId);
        geConUserCompete1.setStatus("1");
        geConUserCompete1.setUserId(Long.valueOf(geConUserCompete.getUserId()));
        //地址数据
        if(geConUserCompete.getAddressId()!=null&&geConUserCompete.getAddressId()!=0){
            GeMyAddress geMyAddress = geMyAddressDao.selectById(geConUserCompete1.getAddressId());
            geConUserCompete1.setName(geMyAddress.getName());
            geConUserCompete1.setPhone(geMyAddress.getPhone());
            geConUserCompete1.setRegion(geMyAddress.getRegion());
            geConUserCompete1.setDetail(geMyAddress.getDetail());
        }
        geConUserCompeteMapper.insert(geConUserCompete1);
        return CommonResult.success("报名成功");
    }

    /**
     * 开始比赛
     */
    @Override
    public void startCompetition(CompetitionDTO competition,HttpServletRequest request)throws Exception {
        String accessToken = request.getHeader("Access_token");
        String openId = TokenUtil.getUsernameFromToken(accessToken);
        String token = request.getHeader("Authorization");
        Map<String, Object> params = new HashMap<>();
        params.put("raceId", competition.getRaceId());
        params.put("itemId", itemIds);
        params.put("userId", Long.valueOf(competition.getUserId()));
        params.put("type", "1");
        params.put("longitude", competition.getLongitude());
        params.put("latitude", competition.getLatitude());
        Map<String, Object> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Tenant-Id", tenantId);
        headers.put("Authorization", "Bearer "+token);
        String result = HttpRequest.sendHttpGetRequest(raceUpUrl,
                new HashMap<>(), headers);
        if (result != null && result != "") {
            JSONObject jsonObject = (JSONObject) JSONObject.parse(result);
            Boolean ok = (Boolean) jsonObject.get("ok");
            Integer code = (Integer) jsonObject.get("code");
            if (ok && code == 0) {
                geConUserCompeteMapper.updateScoreStatus(
                        1,Long.valueOf(competition.getUserId()),
                        competition.getRaceId(),openId);
            }else{
                throw new Exception();
            }
        }
    }

    /**
     * 结束比赛
     */
    @Override
    public void endContest(CompetitionDTO competition,HttpServletRequest request)throws Exception {
        String accessToken = request.getHeader("Access_token");
        String openId = TokenUtil.getUsernameFromToken(accessToken);
        String token = request.getHeader("Authorization");
        Map<String, Object> params = new HashMap<>();
        params.put("raceId", competition.getRaceId());
        params.put("itemId", itemIds);
        params.put("userId", Long.valueOf(competition.getUserId()));
        params.put("type", "2");
        params.put("longitude", competition.getLongitude());
        params.put("latitude", competition.getLatitude());
        Map<String, Object> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Tenant-Id", tenantId);
        headers.put("Authorization", "Bearer "+token);
        String result = HttpRequest.sendHttpGetRequest(raceUpUrl,
                new HashMap<>(), headers);
        if (result != null && result != "") {
            JSONObject jsonObject = (JSONObject) JSONObject.parse(result);
            Boolean ok = (Boolean) jsonObject.get("ok");
            Integer code = (Integer) jsonObject.get("code");
            if (ok && code == 0) {
                geConUserCompeteMapper.updateScoreStatus(
                        2,Long.valueOf(competition.getUserId()),
                        competition.getRaceId(),openId);
            }else{
                throw new Exception();
            }
        }
    }

    /**
     * 我的运动 数据
     * @param openId
     */
    @Transactional
    @Override
    public MySportsDataVO mySportsData(String encryptedData, String iv,String code,String sessionKey,String openId) throws Exception {
        MySportsDataVO mySportsDataVO = new MySportsDataVO();
        LocalDateTime localDateTime = LocalDateTime.now();
        LocalDate date = localDateTime.toLocalDate();
        Month currentMonth = date.getMonth();
        int number = currentMonth.getValue();
        mySportsDataVO.setMonth(number-1);
        mySportsDataVO.setDate(localDateTime);

        //获取自由跑数据
        Map<String, Object> totalByOpenId = geConFreeSportsMapper.getMySportTotalByOpenId(openId);
        double total_distance = (Double) totalByOpenId.get("total_distance");
        BigDecimal total_minutes = (BigDecimal) totalByOpenId.get("total_minutes");

        //获取运动数据
        List<GeConUserCompete> list = geConUserCompeteMapper.selectList(
                new LambdaQueryWrapper<GeConUserCompete>()
                .eq(GeConUserCompete::getOpenId,openId).eq(GeConUserCompete::getStatus,"0")
                        .and(wrapper -> wrapper
                                .isNotNull(GeConUserCompete::getSumMileage)  // sum_mileage 不为 NULL
                                .or()  // OR 条件
                                .isNotNull(GeConUserCompete::getSumDuration)  // sum_duration 不为 NULL
                        ));
        //总时间和总里程
        if(!list.isEmpty()){
            Double totalMileage = list.stream()
                    .mapToDouble(GeConUserCompete::getSumMileage)
                    .sum();
            Long totalSportsTime = list.stream()
                    .mapToLong(GeConUserCompete::getSumDuration)
                    .sum();
            mySportsDataVO.setTotalMileage(String.valueOf(totalMileage+total_distance));
            mySportsDataVO.setTotalSportsTime(String.valueOf(totalSportsTime+total_minutes.longValue()));
        }else{
            mySportsDataVO.setTotalMileage(String.valueOf(total_distance));
            mySportsDataVO.setTotalSportsTime(String.valueOf(total_minutes));
        }


        // 被加密的数据
        byte[] dataByte = DatatypeConverter.parseBase64Binary(encryptedData);
        // 加密秘钥
        byte[] keyByte = DatatypeConverter.parseBase64Binary(sessionKey);
        // 偏移量
        byte[] ivByte = DatatypeConverter.parseBase64Binary(iv);
        // 如果密钥不足16位，那么就补足
        int base = 16;
        if (keyByte.length % base != 0) {
            int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
            keyByte = temp;
        }
        // 初始化
        Security.addProvider(new BouncyCastleProvider());
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding", "BC");
        SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
        AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
        parameters.init(new IvParameterSpec(ivByte));
        cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
        byte[] resultByte = cipher.doFinal(dataByte);
        if (null != resultByte && resultByte.length > 0) {
            String userInfo = new String(resultByte, "UTF-8");
            System.out.println("userInfo:" + userInfo);
            JSONObject jsonObject = (JSONObject) JSONObject.parse(userInfo);
            String stepInfos = jsonObject.getString("stepInfoList");
            JSONArray jsonArray = JSONArray.parseArray(stepInfos);
            if(!jsonArray.isEmpty()){
                jsonArray.stream().forEach(item->{
                    JSONObject json = (JSONObject) JSONObject.parse(item.toString());
                    String timestamp = json.getString("timestamp");
                    String step = json.getString("step");
                    Instant instant = Instant.ofEpochSecond(Long.valueOf(timestamp));
                    ZoneId zoneId = ZoneId.of("GMT");
                    LocalDateTime stepDate = instant.atZone(zoneId).toLocalDateTime().plusDays(1);
                    WxUserStep wxUserStep = wxUserStepMapper.selectOne(new LambdaQueryWrapper<WxUserStep>()
                            .eq(WxUserStep::getOpenId,openId).eq(WxUserStep::getStepDate,stepDate).last("limit 1"));
                    if(Objects.nonNull(wxUserStep)){
                        if(Objects.equals(date,wxUserStep.getStepDate().toLocalDate())){
                            if(!Objects.equals(wxUserStep.getStep(),Integer.valueOf(step))){
                                if(Integer.valueOf(step).intValue()>wxUserStep.getStep().intValue()){
                                    wxUserStep.setStep(Integer.valueOf(step));
                                }else{
                                    wxUserStep.setStep(Integer.valueOf(step).intValue()+wxUserStep.getStep().intValue());
                                }
                                wxUserStepMapper.updateById(wxUserStep);
                            }
                        }
                    }else{
                        WxUserStep wxUserStep1 = new WxUserStep();
                        wxUserStep1.setStep(Integer.valueOf(step));
                        wxUserStep1.setStepDate(stepDate);
                        wxUserStep1.setOpenId(openId);
                        wxUserStepMapper.insert(wxUserStep1);
                    }
                    if(Objects.equals(date,stepDate.toLocalDate())){
                        mySportsDataVO.setTodaySteps(Integer.valueOf(step));
                    }
                });
            }else{
                mySportsDataVO.setTodaySteps(0);
            }
        }else{
            mySportsDataVO.setTodaySteps(0);
        }
        if(Objects.isNull(mySportsDataVO.getTodaySteps())){
            mySportsDataVO.setTodaySteps(0);
        }
        // 获取当前日期
        Date currentDate = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(currentDate);
        // 计算当前日期所在周的周一
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        calendar.add(Calendar.DAY_OF_MONTH, 2 - dayOfWeek);
        List<KeyValue2> keyValue = new ArrayList<>();
        List<KeyValue2> keyValue1 = new ArrayList<>();
        List<KeyValue2> keyValue2 = new ArrayList<>();
//        Map<String,Object> map = new HashMap<>();
//        Map<String,Object> map1 = new HashMap<>();
//        Map<String,Object> map2 = new HashMap<>();
        // 计算前一周的周一
        for (int i = 0; i < 3; i++) {
            calendar.add(Calendar.DAY_OF_MONTH, -7);
            Date previousMonday = calendar.getTime();
            // 输出前四周的周一日期
            System.out.println("第" + (i + 1) + "周前的周一日期：" + new SimpleDateFormat("yyyy-MM-dd").format(previousMonday));
            String str = new SimpleDateFormat("MM/dd").format(previousMonday).toString()+"周";
            if(i==0){//上周
                //里程
                double j = geConUserCompeteMapper.getSumMileageLastWeek(openId);
                double freeSumMileageLastWeek = geConFreeSportsMapper.getSumMileageLastWeekByOpenId(openId);
                //时间
                int k = geConUserCompeteMapper.getSumSportsTimeLastWeek(openId);
                int freeSumSportsTimeLastWeek = geConFreeSportsMapper.getSumSportsTimeLastWeekByOpenId(openId);
                //步数
                int f = wxUserStepMapper.getSumStepLastWeek(openId);
                KeyValue2 keyValue4 = new KeyValue2();
                KeyValue2 keyValue5 = new KeyValue2();
                KeyValue2 keyValue6 = new KeyValue2();
                keyValue4.setKey(str);
                keyValue4.setValue(j+freeSumMileageLastWeek);
                keyValue5.setKey(str);
                keyValue5.setValue(k+freeSumSportsTimeLastWeek);
                keyValue6.setKey(str);
                keyValue6.setValue(f);
                keyValue.add(keyValue4);
                keyValue1.add(keyValue5);
                keyValue2.add(keyValue6);
//                map.put(str,j);
//                map1.put(str,k);
//                map2.put(str,f);
            }else if(i==1){ //前2周
                //里程
                double j = geConUserCompeteMapper.getSumMileageLastWeek1(openId);
                double freeSumMileageLastWeek1 = geConFreeSportsMapper.getSumMileageLastWeek1ByOpenId(openId);
                //时间
                int k = geConUserCompeteMapper.getSumSportsTimeLastWeek1(openId);
                int freeSumSportsTimeLastWeek1 = geConFreeSportsMapper.getSumSportsTimeLastWeek1ByOpenId(openId);
                //步数
                int f = wxUserStepMapper.getSumStepLastWeek1(openId);
                KeyValue2 keyValue4 = new KeyValue2();
                KeyValue2 keyValue5 = new KeyValue2();
                KeyValue2 keyValue6 = new KeyValue2();
                keyValue4.setKey(str);
                keyValue4.setValue(j+freeSumMileageLastWeek1);
                keyValue5.setKey(str);
                keyValue5.setValue(k+freeSumSportsTimeLastWeek1);
                keyValue6.setKey(str);
                keyValue6.setValue(f);
                keyValue.add(keyValue4);
                keyValue1.add(keyValue5);
                keyValue2.add(keyValue6);
//                map.put(str,j);
//                map1.put(str,k);
//                map2.put(str,f);
            }else { //前3周
                //运动里程
                double j = geConUserCompeteMapper.getSumMileageLastWeek2(openId);
                double freeSumMileageLastWeek2 = geConFreeSportsMapper.getSumMileageLastWeek2ByOpenId(openId);
                //运动时间
                int k = geConUserCompeteMapper.getSumSportsTimeLastWeek2(openId);
                int freeSumSportsTimeLastWeek2 = geConFreeSportsMapper.getSumSportsTimeLastWeek2ByOpenId(openId);
                //步数
                int f = wxUserStepMapper.getSumStepLastWeek2(openId);
                KeyValue2 keyValue4 = new KeyValue2();
                KeyValue2 keyValue5 = new KeyValue2();
                KeyValue2 keyValue6 = new KeyValue2();
                keyValue4.setKey(str);
                keyValue4.setValue(j+freeSumMileageLastWeek2);
                keyValue5.setKey(str);
                keyValue5.setValue(k+freeSumSportsTimeLastWeek2);
                keyValue6.setKey(str);
                keyValue6.setValue(f);
                keyValue.add(keyValue4);
                keyValue1.add(keyValue5);
                keyValue2.add(keyValue6);
//                map.put(str,j);
//                map1.put(str,k);
//                map2.put(str,f);
            }
        }
        //倒转顺序
        Collections.reverse(keyValue);
        Collections.reverse(keyValue1);
        Collections.reverse(keyValue2);

        KeyValue2 keyValue4 = new KeyValue2();
        KeyValue2 keyValue5 = new KeyValue2();
        KeyValue2 keyValue6 = new KeyValue2();
        //本周里程
        keyValue4.setKey("本周");
        double sumMileageWeek = geConUserCompeteMapper.getSumMileageWeek(openId);
        double freeSumMileageWeek = geConFreeSportsMapper.getSumMileageWeekByOpenId(openId);
        keyValue4.setValue(sumMileageWeek+freeSumMileageWeek);
        //本周时间
        keyValue5.setKey("本周");
        int sumSportsTimeWeek = geConUserCompeteMapper.getSumSportsTimeWeek(openId);
        int freeSumSportsTimeWeek = geConFreeSportsMapper.getSumSportsTimeWeekByOpenId(openId);
        keyValue5.setValue(sumSportsTimeWeek+freeSumSportsTimeWeek);
        //本周步数
        keyValue6.setKey("本周");
        keyValue6.setValue(wxUserStepMapper.getSumStepWeek(openId));

        keyValue.add(keyValue4);
        keyValue1.add(keyValue5);
        keyValue2.add(keyValue6);
//        map.put("本周",geConUserCompeteMapper.getSumMileageWeek(openId));
//        map1.put("本周",geConUserCompeteMapper.getSumSportsTimeWeek(openId));
//        map2.put("本周",wxUserStepMapper.getSumStepWeek(openId));
        mySportsDataVO.setMileageList(keyValue);
        mySportsDataVO.setSportsTimeList(keyValue1);
        mySportsDataVO.setStepsTimeList(keyValue2);
        return mySportsDataVO;
    }

    @Transactional
    @Override
    public void updateUserCompete(GeConUserCompete geConUserCompete) {
        geConUserCompeteMapper.updateUserCompete1(geConUserCompete);
    }

    @Override
    public CommonResult postSportsData(PostSportsDataDTO postSportsDataDTO) {
        //通过甲板id 查询用户信息
        WxUser wxUser = wxUserDao.selectOne(new LambdaQueryWrapper<WxUser>().eq(WxUser::getDeckId, postSportsDataDTO.getUserId()));
        if(wxUser==null){
            return CommonResult.error("该用户不存在");
        }
        //查出这一条报名信息
        GeConUserCompete one = lambdaQuery().eq(GeConUserCompete::getOpenId, wxUser.getOpenId())
                .eq(GeConUserCompete::getSportsType, postSportsDataDTO.getType())
                .eq(GeConUserCompete::getMotionId, postSportsDataDTO.getMotionId())
                .one();
        if(one==null){
            return CommonResult.error("无此用户报名信息");
        }

        //更新数据信息
        lambdaUpdate().eq(GeConUserCompete::getId,one.getId())
                .set(GeConUserCompete::getSumMileage,postSportsDataDTO.getSumMileage())
                .set(GeConUserCompete::getSumDuration,postSportsDataDTO.getSumDuration())
                .set(GeConUserCompete::getIsComplete,postSportsDataDTO.getIsComplete())
                .update();

        return CommonResult.success("更新成功");
    }

    @Override
    public CommonResult bindingBracelet(BindingBraceletDTO bindingBraceletDTO) {
        //甲板绑定手环
        JSONObject body = new JSONObject();
        body.put("brandId",bindingBraceletDTO.getBracelet());
        body.put("userId",Long.valueOf(bindingBraceletDTO.getUserId()));

        Map<String, Object> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Tenant-Id", tenantId);
        try {
            headers.put("Authorization", "Bearer " + deviceService.deviceLogin());
            String result = HttpRequest.sendHttpPostRequest(braceletUrl, null, headers,body.toString());
            if (result != null && result != "") {
                JSONObject jsonObject = (JSONObject) JSONObject.parse(result);
                Boolean ok = (Boolean) jsonObject.get("ok");
                Integer code = (Integer) jsonObject.get("code");
                if (!ok && code != 0) {
                    System.out.println("甲板绑定手环失败:{}"+result);
                    return CommonResult.error("甲板绑定手环失败");
                }else {
                    lambdaUpdate().eq(GeConUserCompete::getId,bindingBraceletDTO.getEnrollId())
                            .set(GeConUserCompete::getBracelet,bindingBraceletDTO.getBracelet())
                            .update();
                    return CommonResult.success("绑定成功");
                }
            }else {
                return CommonResult.error("甲板绑定手环失败");
            }
        }catch (Exception e){
            return CommonResult.error("向第三方查询用户注册信息异常");
        }
    }

    @Override
    public CommonResult queryScores(String id) {
        GeConUserCompete geConUserCompete = geConUserCompeteMapper.selectById(id);
        if(geConUserCompete.getSumMileage()==null && geConUserCompete.getSumDuration()==null){
            return CommonResult.error("成绩暂无");
        }
        Map<String, Object> result = new HashMap<>();
        result.put("sumDuration",geConUserCompete.getSumDuration());
        result.put("sumMileage",geConUserCompete.getSumMileage());
        return CommonResult.success("查询成功",geConUserCompete);
    }
}
